#!/bin/bash

# 飞书机器人服务器部署脚本
# 服务器信息：
# IP: 47.120.11.77
# 系统: CentOS 7.9 64位
# CPU: 2核 2GB内存

set -e

echo "🚀 开始部署飞书机器人webhook服务器..."

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查SSH连接
check_ssh_connection() {
    print_info "检查SSH连接..."
    
    if ssh -o ConnectTimeout=10 -o BatchMode=yes feishu-server "echo 'SSH连接正常'" 2>/dev/null; then
        print_success "SSH连接正常"
        return 0
    else
        print_error "SSH连接失败，请确保："
        echo "1. 服务器IP地址正确: 47.120.11.77"
        echo "2. SSH密钥配置正确"
        echo "3. 服务器防火墙允许SSH连接"
        echo ""
        echo "请手动连接服务器并运行以下命令："
        echo "ssh feishu-server"
        return 1
    fi
}

# 服务器环境配置
setup_server() {
    print_info "配置服务器环境..."
    
    # 更新系统
    ssh feishu-server "yum update -y"
    
    # 安装必要的软件包
    ssh feishu-server "yum install -y curl wget git vim nginx"
    
    # 安装Node.js
    print_info "安装Node.js..."
    ssh feishu-server "curl -fsSL https://rpm.nodesource.com/setup_18.x | bash -"
    ssh feishu-server "yum install -y nodejs"
    
    # 安装PM2
    ssh feishu-server "npm install -g pm2"
    
    # 创建应用目录
    ssh feishu-server "mkdir -p /opt/feishu-robot"
    
    print_success "服务器环境配置完成"
}

# 配置防火墙
setup_firewall() {
    print_info "配置防火墙..."
    
    # 启用防火墙
    ssh feishu-server "systemctl enable firewalld"
    ssh feishu-server "systemctl start firewalld"
    
    # 开放必要端口
    ssh feishu-server "firewall-cmd --permanent --add-service=ssh"
    ssh feishu-server "firewall-cmd --permanent --add-service=http"
    ssh feishu-server "firewall-cmd --permanent --add-service=https"
    ssh feishu-server "firewall-cmd --permanent --add-port=3000/tcp"
    ssh feishu-server "firewall-cmd --reload"
    
    print_success "防火墙配置完成"
}

# 配置Nginx反向代理
setup_nginx() {
    print_info "配置Nginx反向代理..."
    
    # 创建Nginx配置
    cat > nginx-feishu.conf << 'EOF'
server {
    listen 80;
    server_name 47.120.11.77;
    
    location /webhook/ {
        proxy_pass http://localhost:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        
        # 飞书webhook超时设置
        proxy_connect_timeout 5s;
        proxy_send_timeout 5s;
        proxy_read_timeout 5s;
    }
    
    location / {
        proxy_pass http://localhost:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}
EOF
    
    # 上传配置文件
    scp nginx-feishu.conf feishu-server:/etc/nginx/conf.d/feishu-robot.conf
    
    # 启用配置
    ssh feishu-server "nginx -t && systemctl enable nginx && systemctl restart nginx"
    
    # 清理临时文件
    rm nginx-feishu.conf
    
    print_success "Nginx配置完成"
}

# 部署应用
deploy_app() {
    print_info "部署飞书机器人应用..."
    
    # 创建部署目录
    ssh feishu-server "mkdir -p /opt/feishu-robot"
    
    # 上传项目文件
    print_info "上传项目文件..."
    scp -r src/ feishu-server:/opt/feishu-robot/
    scp package.json feishu-server:/opt/feishu-robot/
    scp config.js feishu-server:/opt/feishu-robot/
    
    # 安装依赖
    ssh feishu-server "cd /opt/feishu-robot && npm install --production"
    
    # 创建PM2配置文件
    cat > ecosystem.config.js << 'EOF'
module.exports = {
  apps: [{
    name: 'feishu-robot',
    script: 'src/app.js',
    cwd: '/opt/feishu-robot',
    instances: 1,
    autorestart: true,
    watch: false,
    max_memory_restart: '1G',
    env: {
      NODE_ENV: 'production',
      PORT: 3000
    },
    error_file: '/opt/feishu-robot/logs/err.log',
    out_file: '/opt/feishu-robot/logs/out.log',
    log_file: '/opt/feishu-robot/logs/combined.log',
    time: true
  }]
};
EOF
    
    # 上传PM2配置
    scp ecosystem.config.js feishu-server:/opt/feishu-robot/
    
    # 创建日志目录
    ssh feishu-server "mkdir -p /opt/feishu-robot/logs"
    
    # 启动应用
    ssh feishu-server "cd /opt/feishu-robot && pm2 start ecosystem.config.js"
    ssh feishu-server "pm2 save"
    ssh feishu-server "pm2 startup"
    
    # 清理临时文件
    rm ecosystem.config.js
    
    print_success "应用部署完成"
}

# 配置SSL证书（可选）
setup_ssl() {
    print_info "配置SSL证书..."
    
    # 安装certbot
    ssh feishu-server "yum install -y epel-release"
    ssh feishu-server "yum install -y certbot python3-certbot-nginx"
    
    print_warning "SSL证书配置需要域名，请手动执行："
    echo "ssh feishu-server"
    echo "certbot --nginx -d your-domain.com"
}

# 测试部署
test_deployment() {
    print_info "测试部署..."
    
    # 等待服务启动
    sleep 5
    
    # 测试健康检查
    if curl -s http://47.120.11.77/webhook/health | grep -q "服务正常运行"; then
        print_success "健康检查通过"
    else
        print_error "健康检查失败"
        return 1
    fi
    
    # 测试webhook端点
    if curl -s http://47.120.11.77/webhook/feishu -X POST -H "Content-Type: application/json" -d '{"type":"test"}' | grep -q "success"; then
        print_success "Webhook端点测试通过"
    else
        print_error "Webhook端点测试失败"
        return 1
    fi
    
    print_success "部署测试完成"
}

# 显示部署信息
show_deployment_info() {
    echo ""
    echo "🎉 飞书机器人服务器部署完成！"
    echo ""
    echo "📋 部署信息："
    echo "   服务器IP: 47.120.11.77"
    echo "   应用端口: 3000"
    echo "   Webhook地址: http://47.120.11.77/webhook/feishu"
    echo "   健康检查: http://47.120.11.77/webhook/health"
    echo ""
    echo "🔧 管理命令："
    echo "   查看应用状态: ssh feishu-server 'pm2 status'"
    echo "   查看日志: ssh feishu-server 'pm2 logs feishu-robot'"
    echo "   重启应用: ssh feishu-server 'pm2 restart feishu-robot'"
    echo "   停止应用: ssh feishu-server 'pm2 stop feishu-robot'"
    echo ""
    echo "📝 飞书配置："
    echo "   在飞书开发者后台配置："
    echo "   请求网址: http://47.120.11.77/webhook/feishu"
    echo "   Encrypt Key: QoMazhHf0AoOd2miHeoK7gT4aFASztop"
    echo "   Verification Token: tKE5o4Swsu4bN9lrrOe7rerCbrAJM4l7"
    echo ""
    echo "⚠️  注意事项："
    echo "   1. 生产环境建议配置HTTPS"
    echo "   2. 定期备份应用数据"
    echo "   3. 监控服务器资源使用情况"
}

# 主函数
main() {
    echo "🚀 飞书机器人服务器部署脚本"
    echo "服务器: 47.120.11.77 (CentOS 7.9)"
    echo ""
    
    # 检查SSH连接
    if ! check_ssh_connection; then
        exit 1
    fi
    
    # 执行部署步骤
    setup_server
    setup_firewall
    setup_nginx
    deploy_app
    
    # 询问是否配置SSL
    read -p "是否配置SSL证书？(y/N): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        setup_ssl
    fi
    
    # 测试部署
    test_deployment
    
    # 显示部署信息
    show_deployment_info
}

# 运行主函数
main "$@" 